<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>2.4.1 Hystrix | weiyonghua&#39;s Blog | YOUR_SUBTITLE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="springclould">
    <meta name="description" content="2.4.1. HystrixHystrix在Spring Cloud中使用了Netflix开发的Hystrix来实现熔断器。下面我们依然通过几个简单的代码示例，进入Hystrix的学习： 通用方式使用Hystrix代码示例：新建一个Maven项目，在pom.xml中添加如下内容： 12345678910111213141516171819202122232425262728293031323334">
<meta name="keywords" content="springclould">
<meta property="og:type" content="article">
<meta property="og:title" content="2.4.1 Hystrix">
<meta property="og:url" content="weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/index.html">
<meta property="og:site_name" content="weiyonghua&#39;s Blog">
<meta property="og:description" content="2.4.1. HystrixHystrix在Spring Cloud中使用了Netflix开发的Hystrix来实现熔断器。下面我们依然通过几个简单的代码示例，进入Hystrix的学习： 通用方式使用Hystrix代码示例：新建一个Maven项目，在pom.xml中添加如下内容： 12345678910111213141516171819202122232425262728293031323334">
<meta property="og:updated_time" content="2017-07-03T08:32:07.343Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="2.4.1 Hystrix">
<meta name="twitter:description" content="2.4.1. HystrixHystrix在Spring Cloud中使用了Netflix开发的Hystrix来实现熔断器。下面我们依然通过几个简单的代码示例，进入Hystrix的学习： 通用方式使用Hystrix代码示例：新建一个Maven项目，在pom.xml中添加如下内容： 12345678910111213141516171819202122232425262728293031323334">
    
        <link rel="alternative" href="/atom.xml" title="weiyonghua&#39;s Blog" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.9">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">weiyonghua</h5>
          <a href="mailto:weiyonghua16@gmail.com" title="weiyonghua16@gmail.com" class="mail">weiyonghua16@gmail.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/1135831485" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://t.qq.com/fy1135831485" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">2.4.1 Hystrix</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">2.4.1 Hystrix</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-07-03T08:24:00.000Z" itemprop="datePublished" class="page-time">
  2017-07-03
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/springclould专栏/">springclould专栏</a></li></ul>

            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#2-4-1-Hystrix"><span class="post-toc-number">1.</span> <span class="post-toc-text">2.4.1. Hystrix</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Hystrix"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">Hystrix</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#通用方式使用Hystrix"><span class="post-toc-number">1.1.1.</span> <span class="post-toc-text">通用方式使用Hystrix</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#代码示例："><span class="post-toc-number">1.1.1.1.</span> <span class="post-toc-text">代码示例：</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#代码地址（任选其一）："><span class="post-toc-number">1.1.1.2.</span> <span class="post-toc-text">代码地址（任选其一）：</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Feign使用Hystrix"><span class="post-toc-number">1.1.2.</span> <span class="post-toc-text">Feign使用Hystrix</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#代码示例"><span class="post-toc-number">1.1.2.1.</span> <span class="post-toc-text">代码示例</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#代码地址（任选其一）"><span class="post-toc-number">1.1.2.2.</span> <span class="post-toc-text">代码地址（任选其一）</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#参考文档："><span class="post-toc-number">1.1.3.</span> <span class="post-toc-text">参考文档：</span></a></li></ol></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-2-4-1-Hystrix"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">2.4.1 Hystrix</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年07月03日 16:24" datetime="2017-07-03T08:24:00.000Z"  itemprop="datePublished">2017-07-03</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/springclould专栏/">springclould专栏</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="2-4-1-Hystrix"><a href="#2-4-1-Hystrix" class="headerlink" title="2.4.1. Hystrix"></a>2.4.1. Hystrix</h1><h2 id="Hystrix"><a href="#Hystrix" class="headerlink" title="Hystrix"></a>Hystrix</h2><p>在Spring Cloud中使用了Netflix开发的Hystrix来实现熔断器。下面我们依然通过几个简单的代码示例，进入Hystrix的学习：</p>
<h3 id="通用方式使用Hystrix"><a href="#通用方式使用Hystrix" class="headerlink" title="通用方式使用Hystrix"></a>通用方式使用Hystrix</h3><h4 id="代码示例："><a href="#代码示例：" class="headerlink" title="代码示例："></a>代码示例：</h4><p>新建一个Maven项目，在pom.xml中添加如下内容：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</div><div class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">"http://maven.apache.org/POM/4.0.0"</span> <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></div><div class="line">  <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</div><div class="line">  <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></div><div class="line"></div><div class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>microservice-consumer-movie-ribbon-with-hystrix<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">packaging</span>&gt;</span>jar<span class="tag">&lt;/<span class="name">packaging</span>&gt;</span></div><div class="line"></div><div class="line">  <span class="tag">&lt;<span class="name">parent</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.itmuch.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-microservice-study<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">  <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></div><div class="line"></div><div class="line">  <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-eureka<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="comment">&lt;!-- 整合ribbon --&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-ribbon<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-actuator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="comment">&lt;!-- 整合hystrix --&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-hystrix<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line">  <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></div></pre></td></tr></table></figure>
<p>启动类：MovieRibbonHystrixApplication.java，使用@EnableCircuitBreaker注解开启断路器功能：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 使用<span class="doctag">@EnableCircuitBreaker</span>注解开启断路器功能</div><div class="line"> * <span class="doctag">@author</span> eacdy</div><div class="line"> */</div><div class="line"><span class="meta">@SpringBootApplication</span></div><div class="line"><span class="meta">@EnableDiscoveryClient</span></div><div class="line"><span class="meta">@EnableCircuitBreaker</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRibbonHystrixApplication</span> </span>&#123;</div><div class="line">  <span class="comment">/**</span></div><div class="line">   * 实例化RestTemplate，通过<span class="doctag">@LoadBalanced</span>注解开启均衡负载能力.</div><div class="line">   * <span class="doctag">@return</span> restTemplate</div><div class="line">   */</div><div class="line">  <span class="meta">@Bean</span></div><div class="line">  <span class="meta">@LoadBalanced</span></div><div class="line">  <span class="function"><span class="keyword">public</span> RestTemplate <span class="title">restTemplate</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> RestTemplate();</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    SpringApplication.run(MovieRibbonHystrixApplication.class, args);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>实体类：User.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</div><div class="line">  <span class="keyword">private</span> Long id;</div><div class="line">  <span class="keyword">private</span> String username;</div><div class="line">  <span class="keyword">private</span> Integer age;</div><div class="line">  ...</div><div class="line">  <span class="comment">// getters and setters</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>Hystrix业务类：RibbonHystrixService.java，使用@HystrixCommand注解指定当该方法发生异常时调用的方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Service</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RibbonHystrixService</span> </span>&#123;</div><div class="line">  <span class="meta">@Autowired</span></div><div class="line">  <span class="keyword">private</span> RestTemplate restTemplate;</div><div class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger LOGGER = LoggerFactory.getLogger(RibbonHystrixService.class);</div><div class="line"></div><div class="line">  <span class="comment">/**</span></div><div class="line">   * 使用<span class="doctag">@HystrixCommand</span>注解指定当该方法发生异常时调用的方法</div><div class="line">   * <span class="doctag">@param</span> id id</div><div class="line">   * <span class="doctag">@return</span> 通过id查询到的用户</div><div class="line">   */</div><div class="line">  <span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"fallback"</span>)</div><div class="line">  <span class="function"><span class="keyword">public</span> User <span class="title">findById</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.restTemplate.getForObject(<span class="string">"http://microservice-provider-user/"</span> + id, User.class);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">/**</span></div><div class="line">   * hystrix fallback方法</div><div class="line">   * <span class="doctag">@param</span> id id</div><div class="line">   * <span class="doctag">@return</span> 默认的用户</div><div class="line">   */</div><div class="line">  <span class="function"><span class="keyword">public</span> User <span class="title">fallback</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">    RibbonHystrixService.LOGGER.info(<span class="string">"异常发生，进入fallback方法，接收的参数：id = &#123;&#125;"</span>, id);</div><div class="line">    User user = <span class="keyword">new</span> User();</div><div class="line">    user.setId(-<span class="number">1L</span>);</div><div class="line">    user.setUsername(<span class="string">"default username"</span>);</div><div class="line">    user.setAge(<span class="number">0</span>);</div><div class="line">    <span class="keyword">return</span> user;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>controller：RibbonHystrixController.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@RestController</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RibbonHystrixController</span> </span>&#123;</div><div class="line">  <span class="meta">@Autowired</span></div><div class="line">  <span class="keyword">private</span> RibbonHystrixService ribbonHystrixService;</div><div class="line"></div><div class="line">  <span class="meta">@GetMapping</span>(<span class="string">"/ribbon/&#123;id&#125;"</span>)</div><div class="line">  <span class="function"><span class="keyword">public</span> User <span class="title">findById</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.ribbonHystrixService.findById(id);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>application.yml</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="attr">server:</span></div><div class="line"><span class="attr">  port:</span> <span class="number">8011</span></div><div class="line"><span class="attr">spring:</span></div><div class="line"><span class="attr">  application:</span></div><div class="line"><span class="attr">    name:</span> <span class="string">microservice-consumer-movie-ribbon-with-hystrix</span></div><div class="line"><span class="attr">eureka:</span></div><div class="line"><span class="attr">  client:</span></div><div class="line"><span class="attr">    serviceUrl:</span></div><div class="line"><span class="attr">      defaultZone:</span> <span class="attr">http://discovery:8761/eureka/</span></div><div class="line"><span class="attr">  instance:</span></div><div class="line"><span class="attr">    hostname:</span> <span class="string">ribbon</span>          <span class="comment"># 此处，preferIpAddress不设置或者设为false，不能设为true，否则影响turbine的测试。turbine存在的问题：eureka.instance.hostname一致时只能检测到一个节点，会造成turbine数据不完整</span></div></pre></td></tr></table></figure>
<p>验证：</p>
<ol>
<li><p>启动注册中心：microservice-discovery-eureka</p>
</li>
<li><p>启动服务提供方：microservice-provider-user</p>
</li>
<li><p>启动服务消费方：microservice-consumer-movie-ribbon-with-hystrix</p>
</li>
<li><p>访问：<a href="http://localhost:8011/ribbon/1" target="_blank" rel="external">http://localhost:8011/ribbon/1</a>，获得结果：<code>{&quot;id&quot;:1,&quot;username&quot;:&quot;Tom&quot;,&quot;age&quot;:12}</code></p>
</li>
<li><p>关闭服务提供方：microservice-provider-user，访问<a href="http://localhost:8011/ribbon/1" target="_blank" rel="external">http://localhost:8011/ribbon/1</a>，获得结果：<code>{&quot;id&quot;:-1,&quot;username&quot;:&quot;default username&quot;,&quot;age&quot;:0}</code>，另外日志打印：<code>c.i.c.s.u.service.RibbonHystrixService   : 异常发生，进入fallback方法，接收的参数：id = 1</code> 。</p>
<p>​</p>
</li>
</ol>
<p>注意：</p>
<blockquote>
<ol>
<li>本示例代码在microservice-consumer-movie-ribbon基础上修改而来</li>
<li>如对本示例涉及的知识点有疑难，请查看上一章《服务消费者》</li>
</ol>
</blockquote>
<h4 id="代码地址（任选其一）："><a href="#代码地址（任选其一）：" class="headerlink" title="代码地址（任选其一）："></a>代码地址（任选其一）：</h4><blockquote>
<ol>
<li><a href="http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-consumer-movie-ribbon-with-hystrix" target="_blank" rel="external">http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-consumer-movie-ribbon-with-hystrix</a></li>
<li><a href="https://github.com/eacdy/spring-cloud-study/tree/master/microservice-consumer-movie-ribbon-with-hystrix" target="_blank" rel="external">https://github.com/eacdy/spring-cloud-study/tree/master/microservice-consumer-movie-ribbon-with-hystrix</a></li>
</ol>
</blockquote>
<h3 id="Feign使用Hystrix"><a href="#Feign使用Hystrix" class="headerlink" title="Feign使用Hystrix"></a>Feign使用Hystrix</h3><h4 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h4><p>在Feign中使用Hystrix是非常简单的事情，因为Feign已经集成了Hystrix。我们使用microservice-consumer-movie-feign-with-hystrix项目的代码做一点修改，将其中的UserClient.java修改为如下即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 使用<span class="doctag">@FeignClient</span>注解的fallback属性，指定fallback类</div><div class="line"> * <span class="doctag">@author</span> eacdy</div><div class="line"> */</div><div class="line"><span class="meta">@FeignClient</span>(name = <span class="string">"microservice-provider-user"</span>, fallback = HystrixClientFallback.class)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserFeignHystrixClient</span> </span>&#123;</div><div class="line">  <span class="meta">@RequestMapping</span>(<span class="string">"/&#123;id&#125;"</span>)</div><div class="line">  <span class="function"><span class="keyword">public</span> User <span class="title">findByIdFeign</span><span class="params">(@RequestParam(<span class="string">"id"</span>)</span> Long id)</span>;</div><div class="line"></div><div class="line">  <span class="comment">/**</span></div><div class="line">   * 这边采取了和Spring Cloud官方文档相同的做法，将fallback类作为内部类放入Feign的接口中，当然也可以单独写一个fallback类。</div><div class="line">   * <span class="doctag">@author</span> eacdy</div><div class="line">   */</div><div class="line">  <span class="meta">@Component</span></div><div class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">HystrixClientFallback</span> <span class="keyword">implements</span> <span class="title">UserFeignHystrixClient</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger LOGGER = LoggerFactory.getLogger(HystrixClientFallback.class);</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * hystrix fallback方法</div><div class="line">     * <span class="doctag">@param</span> id id</div><div class="line">     * <span class="doctag">@return</span> 默认的用户</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">findByIdFeign</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">      HystrixClientFallback.LOGGER.info(<span class="string">"异常发生，进入fallback方法，接收的参数：id = &#123;&#125;"</span>, id);</div><div class="line">      User user = <span class="keyword">new</span> User();</div><div class="line">      user.setId(-<span class="number">1L</span>);</div><div class="line">      user.setUsername(<span class="string">"default username"</span>);</div><div class="line">      user.setAge(<span class="number">0</span>);</div><div class="line">      <span class="keyword">return</span> user;</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样就完成了，是不是很简单呢？测试过程类似通用方式。</p>
<p>注意：</p>
<blockquote>
<ol>
<li>本示例代码在microservice-consumer-movie-feign基础上修改而来</li>
<li>如对本示例涉及的知识点有疑难，请查看上一章《服务消费者》</li>
</ol>
</blockquote>
<h4 id="代码地址（任选其一）"><a href="#代码地址（任选其一）" class="headerlink" title="代码地址（任选其一）"></a>代码地址（任选其一）</h4><blockquote>
<ol>
<li><a href="http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-consumer-movie-feign-with-hystrix" target="_blank" rel="external">http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-consumer-movie-feign-with-hystrix</a></li>
<li><a href="https://github.com/eacdy/spring-cloud-study/tree/master/microservice-consumer-movie-feign-with-hystrix" target="_blank" rel="external">https://github.com/eacdy/spring-cloud-study/tree/master/microservice-consumer-movie-feign-with-hystrix</a></li>
</ol>
</blockquote>
<h3 id="参考文档："><a href="#参考文档：" class="headerlink" title="参考文档："></a>参考文档：</h3><blockquote>
<ol>
<li><a href="https://msdn.microsoft.com/en-us/library/dn589784.aspx" target="_blank" rel="external">https://msdn.microsoft.com/en-us/library/dn589784.aspx</a></li>
<li><a href="http://martinfowler.com/bliki/CircuitBreaker.html" target="_blank" rel="external">http://martinfowler.com/bliki/CircuitBreaker.html</a></li>
<li><a href="http://particular.net/blog/protect-your-software-with-the-circuit-breaker-design-pattern" target="_blank" rel="external">http://particular.net/blog/protect-your-software-with-the-circuit-breaker-design-pattern</a></li>
<li><a href="https://github.com/Netflix/Hystrix/wiki/How-it-Works#flow-chart" target="_blank" rel="external">https://github.com/Netflix/Hystrix/wiki/How-it-Works#flow-chart</a></li>
<li><a href="https://segmentfault.com/a/1190000005988895" target="_blank" rel="external">https://segmentfault.com/a/1190000005988895</a></li>
</ol>
</blockquote>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-07-03T08:32:07.343Z" itemprop="dateUpdated">2017年7月3日 16:32</time>
</span><br>


        这里写留言或版权声明：<a href="/2017/07/03/2-4-1-Hystrix/" target="_blank" rel="external">weiyonghua&#39;s Blog/2017/07/03/2-4-1-Hystrix/</a>
    </div>
    <footer>
        <a href="weiyonghua's Blog">
            <img src="/img/avatar.jpg" alt="weiyonghua">
            weiyonghua
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/springclould/">springclould</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/&title=《2.4.1 Hystrix》 — weiyonghua's Blog&pic=weiyonghua's Blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/&title=《2.4.1 Hystrix》 — weiyonghua's Blog&source=YOUR_DESC" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《2.4.1 Hystrix》 — weiyonghua's Blog&url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/&via=weiyonghua's Blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/07/03/2-5-配置中心/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">2.5 配置中心</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/07/03/2-4-2-Hystrix-Dashboard/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">2.4.2 Hystrix Dashboard</h4>
      </a>
    </div>
  
</nav>



    

<div class="comments" id="comments">
    <div class="ds-thread" data-thread-key="2-4-1-Hystrix" data-title="2.4.1 Hystrix" data-url="weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/"></div>
</div>
<script>
lazyScripts.push('//cdn.bootcss.com/marked/0.3.6/marked.min.js');

var duoshuoQuery = {short_name:'ysblog', theme: 'none'};
lazyScripts.push('/js/embed.min.js?v=1.4.9');


</script>







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.jpg" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a></span>
            <span>weiyonghua's Blog &copy; 2015 - 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/&title=《2.4.1 Hystrix》 — weiyonghua's Blog&pic=weiyonghua's Blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/&title=《2.4.1 Hystrix》 — weiyonghua's Blog&source=YOUR_DESC" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《2.4.1 Hystrix》 — weiyonghua's Blog&url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/&via=weiyonghua's Blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=weiyonghua's Blog/2017/07/03/2-4-1-Hystrix/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



</script>

<script src="/js/main.min.js?v=1.4.9"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.9" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
